{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "from __future__ import print_function, absolute_import\n",
    "from gm.api import *\n",
    "import datetime\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import talib\n",
    "# 可以直接提取数据，掘金终端需要打开，接口取数是通过网络请求的方式，效率一般，行情数据可通过subscribe订阅方式\n",
    "# 设置token， 查看已有token ID,在用户-密钥管理里获取\n",
    "set_token('bf739ec28ad507f391a3c3e99ed0365007da88f8')\n",
    "# set_token('ca9c4532786a122aa5ceb3fd726432862e046f91') # 135账户\n",
    "# data = stk_get_index_constituents(index='SHSE.000300')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\bww\\AppData\\Local\\Temp\\ipykernel_16652\\3501056517.py:34: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  data['DIFF'].iloc[0] = 0\n",
      "C:\\Users\\bww\\AppData\\Local\\Temp\\ipykernel_16652\\3501056517.py:35: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  data['DEA'].iloc[0] = 0\n",
      "C:\\Users\\bww\\AppData\\Local\\Temp\\ipykernel_16652\\3501056517.py:36: SettingWithCopyWarning: \n",
      "A value is trying to be set on a copy of a slice from a DataFrame\n",
      "\n",
      "See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n",
      "  data['MACD'].iloc[0] = 0\n"
     ]
    }
   ],
   "source": [
    "# MACD指标计算\n",
    "# 计算12日和26日的EMA数据\n",
    "# 计算12日EMA:EMA(12) = 2/(12+1) * 今日收盘价(12) + 11/(12+1) * 昨日EMA(12)\n",
    "# 计算26日EMA:EMA(26) = 2/(26+1) * 今日收盘价(26) + 25/(26+1) * 昨日EMA(26)\n",
    "# 计算DEA:DEA = 2/(9+1) * 今日DIFF + 8/(9+1) * 昨日DEA\n",
    "# 计算MACD：MACD = 2 * (DIFF-DEA)\n",
    "# 注意：上市首日DIFF、DEA、MACD均为0，次日的EMA均按照上市首日的收盘价计算\n",
    "\n",
    "def MACD(symbol, start_time, end_time):\n",
    "    '''计算MACD指标\n",
    "        输入参数：symbol <- str      标的代码 （2005年以前上市的不可用）\n",
    "                start_time <- str  起始时间\n",
    "                end_time <- str    结束时间\n",
    "        输出数据：\n",
    "                macd <- dataframe  macd指标，包括DIFF、DEA、MACD\n",
    "\n",
    "    '''\n",
    "    # 取历史数据，取到上市首日\n",
    "    data = history(symbol=symbol, frequency='1d', start_time='2005-01-01', end_time=end_time, fields='symbol,bob,close',\n",
    "                   df=True)\n",
    "    # 将数据转化为dataframe格式\n",
    "    data['bob'] = data['bob'].apply(lambda x: x.strftime('%Y-%m-%d')).tolist()\n",
    "\n",
    "    # 计算EMA(12)和EMA(16)\n",
    "    data['EMA12'] = data['close'].ewm(alpha=2 / 13, adjust=False).mean()\n",
    "    data['EMA26'] = data['close'].ewm(alpha=2 / 27, adjust=False).mean()\n",
    "\n",
    "    # 计算DIFF、DEA、MACD\n",
    "    data['DIFF'] = data['EMA12'] - data['EMA26']\n",
    "    data['DEA'] = data['DIFF'].ewm(alpha=2 / 10, adjust=False).mean()\n",
    "    data['MACD'] = 2 * (data['DIFF'] - data['DEA'])\n",
    "\n",
    "    # 上市首日，DIFF、DEA、MACD均为0\n",
    "    data['DIFF'].iloc[0] = 0\n",
    "    data['DEA'].iloc[0] = 0\n",
    "    data['MACD'].iloc[0] = 0\n",
    "\n",
    "    # 按照起止时间筛选\n",
    "    MACD = data[(data['bob'] >= start_time)]\n",
    "\n",
    "    return MACD\n",
    "\n",
    "# 测试一下\n",
    "a = MACD(symbol = 'DCE.y2101',start_time = '2020-01-01',end_time = '2020-10-22')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>symbol</th>\n",
       "      <th>close</th>\n",
       "      <th>bob</th>\n",
       "      <th>EMA12</th>\n",
       "      <th>EMA26</th>\n",
       "      <th>DIFF</th>\n",
       "      <th>DEA</th>\n",
       "      <th>MACD</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6508.0</td>\n",
       "      <td>2020-01-16</td>\n",
       "      <td>6508.00000000</td>\n",
       "      <td>6508.00000000</td>\n",
       "      <td>0.00000000</td>\n",
       "      <td>0.00000000</td>\n",
       "      <td>0.00000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6534.0</td>\n",
       "      <td>2020-01-17</td>\n",
       "      <td>6512.00000000</td>\n",
       "      <td>6509.92592593</td>\n",
       "      <td>2.07407407</td>\n",
       "      <td>0.41481481</td>\n",
       "      <td>3.31851852</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6580.0</td>\n",
       "      <td>2020-01-20</td>\n",
       "      <td>6522.46153846</td>\n",
       "      <td>6515.11659808</td>\n",
       "      <td>7.34494038</td>\n",
       "      <td>1.80083993</td>\n",
       "      <td>11.08820091</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6418.0</td>\n",
       "      <td>2020-01-21</td>\n",
       "      <td>6506.39053254</td>\n",
       "      <td>6507.92277600</td>\n",
       "      <td>-1.53224346</td>\n",
       "      <td>1.13422325</td>\n",
       "      <td>-5.33293341</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6508.0</td>\n",
       "      <td>2020-01-22</td>\n",
       "      <td>6506.63814292</td>\n",
       "      <td>6507.92849630</td>\n",
       "      <td>-1.29035337</td>\n",
       "      <td>0.64930793</td>\n",
       "      <td>-3.87932260</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>178</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6992.0</td>\n",
       "      <td>2020-10-16</td>\n",
       "      <td>7042.14368845</td>\n",
       "      <td>6944.05412991</td>\n",
       "      <td>98.08955854</td>\n",
       "      <td>119.18285978</td>\n",
       "      <td>-42.18660248</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>179</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6846.0</td>\n",
       "      <td>2020-10-19</td>\n",
       "      <td>7011.96773638</td>\n",
       "      <td>6936.79086102</td>\n",
       "      <td>75.17687535</td>\n",
       "      <td>110.38166289</td>\n",
       "      <td>-70.40957508</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>180</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>6938.0</td>\n",
       "      <td>2020-10-20</td>\n",
       "      <td>7000.58808463</td>\n",
       "      <td>6936.88042687</td>\n",
       "      <td>63.70765775</td>\n",
       "      <td>101.04686187</td>\n",
       "      <td>-74.67840823</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>181</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>7038.0</td>\n",
       "      <td>2020-10-21</td>\n",
       "      <td>7006.34376392</td>\n",
       "      <td>6944.37076562</td>\n",
       "      <td>61.97299829</td>\n",
       "      <td>93.23208915</td>\n",
       "      <td>-62.51818172</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>182</th>\n",
       "      <td>DCE.y2101</td>\n",
       "      <td>7156.0</td>\n",
       "      <td>2020-10-22</td>\n",
       "      <td>7029.36780024</td>\n",
       "      <td>6960.04700521</td>\n",
       "      <td>69.32079503</td>\n",
       "      <td>88.44983033</td>\n",
       "      <td>-38.25807060</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>183 rows × 8 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "        symbol   close         bob          EMA12          EMA26         DIFF  \\\n",
       "0    DCE.y2101  6508.0  2020-01-16  6508.00000000  6508.00000000   0.00000000   \n",
       "1    DCE.y2101  6534.0  2020-01-17  6512.00000000  6509.92592593   2.07407407   \n",
       "2    DCE.y2101  6580.0  2020-01-20  6522.46153846  6515.11659808   7.34494038   \n",
       "3    DCE.y2101  6418.0  2020-01-21  6506.39053254  6507.92277600  -1.53224346   \n",
       "4    DCE.y2101  6508.0  2020-01-22  6506.63814292  6507.92849630  -1.29035337   \n",
       "..         ...     ...         ...            ...            ...          ...   \n",
       "178  DCE.y2101  6992.0  2020-10-16  7042.14368845  6944.05412991  98.08955854   \n",
       "179  DCE.y2101  6846.0  2020-10-19  7011.96773638  6936.79086102  75.17687535   \n",
       "180  DCE.y2101  6938.0  2020-10-20  7000.58808463  6936.88042687  63.70765775   \n",
       "181  DCE.y2101  7038.0  2020-10-21  7006.34376392  6944.37076562  61.97299829   \n",
       "182  DCE.y2101  7156.0  2020-10-22  7029.36780024  6960.04700521  69.32079503   \n",
       "\n",
       "              DEA         MACD  \n",
       "0      0.00000000   0.00000000  \n",
       "1      0.41481481   3.31851852  \n",
       "2      1.80083993  11.08820091  \n",
       "3      1.13422325  -5.33293341  \n",
       "4      0.64930793  -3.87932260  \n",
       "..            ...          ...  \n",
       "178  119.18285978 -42.18660248  \n",
       "179  110.38166289 -70.40957508  \n",
       "180  101.04686187 -74.67840823  \n",
       "181   93.23208915 -62.51818172  \n",
       "182   88.44983033 -38.25807060  \n",
       "\n",
       "[183 rows x 8 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0       0.00000000\n",
       "1       2.07407407\n",
       "2       7.34494038\n",
       "3      -1.53224346\n",
       "4      -1.29035337\n",
       "          ...     \n",
       "178    98.08955854\n",
       "179    75.17687535\n",
       "180    63.70765775\n",
       "181    61.97299829\n",
       "182    69.32079503\n",
       "Name: DIFF, Length: 183, dtype: float64"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a['DIFF']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[         nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan  74.57602555  84.78519342  93.35140336\n",
      "  89.86763875  86.23548726  80.78471213  71.44276762  62.77523108\n",
      "  51.8205935   59.55392087  61.31967082  68.2199018   72.62015333\n",
      "  78.08964767  73.98256242  68.23050723  62.47555645  55.39611711\n",
      "  57.36979004  61.3222387   69.77928197  77.22398862  83.43295469\n",
      "  86.37779751  91.58644571  92.47385117  94.37704654 101.48422473\n",
      "  99.34306482  96.01385353  94.05099429 100.89919371 102.90533621\n",
      " 107.15318397 117.04031748 131.68592052 147.76719289 141.8548015\n",
      " 125.87271723 103.82236382  87.64722346  74.56592958  63.57598768\n",
      "  44.03312392  45.07125204  55.40342702  59.68844849  61.85993455\n",
      "  58.51341751  49.46771886  33.26104526  25.75833843  25.49790224\n",
      "  31.84067597] [         nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan  71.2693945   73.97255429  77.8483241\n",
      "  80.25218703  81.44884708  81.31602009  79.34136959  76.02814189\n",
      "  71.18663221  68.86008995  67.35200612  67.52558526  68.54449887\n",
      "  70.45352863  71.15933539  70.57356976  68.9539671   66.2423971\n",
      "  64.46787569  63.83874829  65.02685503  67.46628175  70.65961633\n",
      "  73.80325257  77.3598912   80.38268319  83.18155586  86.84208964\n",
      "  89.34228467  90.67659844  91.35147761  93.26102083  95.18988391\n",
      "  97.58254392 101.47409863 107.51646301 115.56660899 120.82424749\n",
      " 121.83394144 118.23162591 112.11474542 104.60498226  96.39918334\n",
      "  85.92597146  77.75502757  73.28470746  70.56545567  68.82435145\n",
      "  66.76216466  63.3032755   57.29482945  50.98753125  45.88960545\n",
      "  43.07981955] [         nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan          nan          nan          nan\n",
      "          nan          nan   3.30663105  10.81263914  15.50307925\n",
      "   9.61545172   4.78664018  -0.53130796  -7.89860198 -13.25291081\n",
      " -19.36603871  -9.30616907  -6.0323353    0.69431654   4.07565446\n",
      "   7.63611904   2.82322703  -2.34306252  -6.47841065 -10.84627999\n",
      "  -7.09808565  -2.51650959   4.75242694   9.75770688  12.77333835\n",
      "  12.57454494  14.22655451  12.09116798  11.19549068  14.6421351\n",
      "  10.00078015   5.33725509   2.69951668   7.63817288   7.7154523\n",
      "   9.57064005  15.56621884  24.16945751  32.2005839   21.03055401\n",
      "   4.03877579 -14.40926209 -24.46752196 -30.03905267 -32.82319566\n",
      " -41.89284754 -32.68377553 -17.88128044 -10.87700718  -6.96441689\n",
      "  -8.24874715 -13.83555664 -24.03378419 -25.22919281 -20.3917032\n",
      " -11.23914358]\n"
     ]
    }
   ],
   "source": [
    "data = history(symbol='DCE.y2101', frequency='1d', start_time= '2020-06-22', end_time= '2020-10-22', fields='symbol,bob,close',\n",
    "                   df=True)\n",
    "MACD_macd, MACD_macdsignal, MACD_macdhist = talib.MACD(data['close'].values, fastperiod=12, slowperiod=20, signalperiod=9)\n",
    "# 判断金叉和死叉\n",
    "# death_cross = (MACD_macd[-2] > MACD_macdsignal[-2]) & (MACD_macd[-1] <= MACD_macdsignal[-1])\n",
    "# golden_cross = (MACD_macd[-2] < MACD_macdsignal[-2]) & (MACD_macd[-1] >= MACD_macdsignal[-1])\n",
    "\n",
    "print(MACD_macd, MACD_macdsignal, MACD_macdhist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MACD: [       nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan 0.23846686 0.24265078 0.24316353\n",
      " 0.21845798 0.1990054  0.21181029 0.20427212 0.14977046 0.15083303\n",
      " 0.15313751]\n",
      "MACD Signal: [       nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan        nan        nan        nan\n",
      "        nan        nan        nan 0.39277815 0.36275268 0.33883485\n",
      " 0.31475948 0.29160866 0.27564898 0.26137361 0.23905298 0.22140899\n",
      " 0.20775469]\n",
      "MACD Histogram: [        nan         nan         nan         nan         nan         nan\n",
      "         nan         nan         nan         nan         nan         nan\n",
      "         nan         nan         nan         nan         nan         nan\n",
      "         nan         nan         nan         nan         nan         nan\n",
      "         nan         nan         nan         nan         nan         nan\n",
      "         nan         nan         nan -0.15431129 -0.1201019  -0.09567132\n",
      " -0.09630149 -0.09260326 -0.0638387  -0.05710149 -0.08928252 -0.07057597\n",
      " -0.05461719]\n"
     ]
    }
   ],
   "source": [
    "import talib\n",
    "import numpy as np\n",
    "\n",
    "# 示例数据，假设这是收盘价数据\n",
    "close_prices = np.array([44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28, 46.00, 46.03, 46.41, 46.22, 45.64, 46.21, 46.25, 46.12, 45.94, 46.03, 46.41, 46.22, 45.64, 46.21, 46.25, 46.12, 45.94, 46.03, 45.61, 46.28, 46.28, 46.00, 46.03, 46.41, 46.22, 45.64, 46.21, 46.25])\n",
    "# 计算 MACD\n",
    "macd, macdsignal, macdhist = talib.MACD(close_prices, fastperiod=12, slowperiod=26, signalperiod=9)\n",
    "\n",
    "# 打印结果\n",
    "print(\"MACD:\", macd)\n",
    "print(\"MACD Signal:\", macdsignal)\n",
    "print(\"MACD Histogram:\", macdhist)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
